<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="话单编号" prop="ucid">
        <el-input
          v-model="queryParams.ucid"
          placeholder="请输入话单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主叫ID" prop="callerId">
        <el-input
          v-model="queryParams.callerId"
          placeholder="请输入主叫ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="被叫ID" prop="answerId">
        <el-input
          v-model="queryParams.answerId"
          placeholder="请输入被叫ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通话状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择通话状态" clearable>
          <el-option
            v-for="dict in dict.type.call_sheet_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="switchPermission"
            v-hasPermi="['system:config:edit']"
          >{{ this.configKey == 0 ? '关闭女打男权限' : '开启女打男权限'}}</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

    <el-table v-loading="loading" :data="callSheetInfoList">

      <el-table-column label="话单详情" align="center" prop="ucid" type="expand">
        <template slot-scope="scope">
          <callInfo :ucid="scope.row.ucid"></callInfo>
        </template>
      </el-table-column>
      <el-table-column label="通话唯一标识" align="center" prop="ucid"/>
      <el-table-column label="主叫ID" align="center" prop="callPlatformId">
        <template slot-scope="scope">
          <a v-if="scope.row.callSex === 1" style="color: #FF6EC7" @click="toUserInfo(scope.row.callPlatformId)">{{ scope.row.callPlatformId }}
          </a>
          <a v-else style="color: #7099F9" @click="toUserInfo(scope.row.callPlatformId)">{{ scope.row.callPlatformId }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="主叫平台" align="center" prop="callBranch">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_branch" :value="scope.row.callBranch"/>
        </template>
      </el-table-column>
      <el-table-column label="被叫ID" align="center" prop="answerPlatformId">
        <template slot-scope="scope">
          <a v-if="scope.row.answerSex === 1" style="color: #FF6EC7" @click="toUserInfo(scope.row.answerPlatformId)">{{ scope.row.answerPlatformId }}
          </a>
          <a v-else style="color: #7099F9" @click="toUserInfo(scope.row.answerPlatformId)">{{ scope.row.answerPlatformId }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="被叫平台" align="center" prop="answerBranch">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_branch" :value="scope.row.answerBranch"/>
        </template>
      </el-table-column>
      <el-table-column label="通话状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status===9">正在通话</el-tag>
          <el-tag type="info" v-if="scope.row.status===0">等待接通</el-tag>
          <el-tag type="danger" v-if="scope.row.status===1||scope.row.status===2||scope.row.status===5">未接挂断
          </el-tag>
          <el-tag type="danger" v-if="scope.row.status===6||scope.row.status===7||scope.row.status===8">已接挂断
          </el-tag>
          <el-tag type="warning" v-if="scope.row.status===3 ">无人接听</el-tag>
          <el-tag type="" v-if="scope.row.status===4">被叫忙碌</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接通状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status==9 || scope.row.duration>0">已接通</el-tag>
          <el-tag type="danger" v-else>未接通</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="通话时长" align="center" prop="duration">
        <template slot-scope="scope">
          <span v-if="scope.row.status!==9">{{ Math.floor(scope.row.duration / 60) }}分钟{{ scope.row.duration % 60 }}秒</span>
          <span v-else>{{ refreshCallTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="通话单价" align="center" prop="callPrice"/>
      <el-table-column label="主叫支付" align="center" prop="payCost"/>
      <el-table-column label="被叫收益" align="center" prop="earnCost"/>
      <!-- <el-table-column label="录音信息" align="center" prop="record" /> -->
      <el-table-column label="心跳次数" align="center" prop="keepLiveTimes"/>
      <el-table-column label="计费时长" align="center" prop="priceTimes"/>
      <el-table-column label="免费时长" align="center" prop="freeTimes"/>
      <el-table-column label="收费时长" align="center" prop="feeTimes"/>
      <el-table-column label="状态备注" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.call_sheet_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="通话备注" align="center" prop="remark">
      </el-table-column>
      <el-table-column label="振铃时间" align="center" prop="ringTime"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="接通时间" align="center" prop="startTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="挂断时间" align="center" prop="stopTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.stopTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.status!==9" size="mini" type="text" icon="el-icon-close"
                     @click="handleCancel(scope.row)" v-hasPermi="['system:callSheetInfo:cancel']">强制挂断
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--拒绝审核 -->
    <el-dialog title="强制挂断" :visible.sync="openCancel" width="500px" append-to-body>
      <el-form ref="form" :model="bo" :rules="rules" label-width="80px">
        <el-form-item label="操作备注" prop="remark">
          <el-input v-model="bo.remark" placeholder="请输入话单备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="toCancel">确 定</el-button>
        <el-button @click="openCancel=false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addCallSheetInfo, cancelCall,
  delCallSheetInfo,
  getCallSheetInfo,
  listCallSheetInfo,
  updateCallSheetInfo
} from "@/api/service/call/callSheetInfo";

import callInfo from "./callInfo.vue";
import {updateConfigByKey, getConfigKeys} from "@/api/system/config";

export default {
  name: "CallSheetInfo",
  dicts: ['call_sheet_status', 'sys_branch'],
  components: {
    callInfo,
  },
  data() {
    return {
      bo: {},
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通话话单表格数据
      callSheetInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openCancel: false,
      configKey: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        callerId: undefined,
        callerPlat: undefined,
        answerId: undefined,
        answerPlat: undefined,
        ucid: undefined,
        status: undefined,
        ringTime: undefined,
        startTime: undefined,
        stopTime: undefined,
        duration: undefined,
        callPrice: undefined,
        payPrice: undefined,
        payCost: undefined,
        earnPrice: undefined,
        earnCost: undefined,
        record: undefined,
        keepLiveTimes: undefined,
        priceTimes: undefined,
        scoreFlag: undefined,
        callDate: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "通话类型不能为空", trigger: "change"}
        ],
        callerId: [
          {required: true, message: "主叫用户id不能为空", trigger: "blur"}
        ],
        callerPlat: [
          {required: true, message: "主叫客户端渠道号，默认0不能为空", trigger: "blur"}
        ],
        answerId: [
          {required: true, message: "主叫用户id不能为空", trigger: "blur"}
        ],
        answerPlat: [
          {required: true, message: "主叫客户端渠道号，默认0不能为空", trigger: "blur"}
        ],
        ucid: [
          {required: true, message: "通话唯一标识不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "通话状态不能为空", trigger: "change"}
        ],
        ringTime: [
          {required: true, message: "被叫振铃时间不能为空", trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "接通时间不能为空", trigger: "blur"}
        ],
        stopTime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"}
        ],
        duration: [
          {required: true, message: "通话时长，秒不能为空", trigger: "blur"}
        ],
        callPrice: [
          {required: true, message: "通话单价不能为空", trigger: "blur"}
        ],
        payPrice: [
          {required: true, message: "主叫支付单价不能为空", trigger: "blur"}
        ],
        payCost: [
          {required: true, message: "主叫支付费用不能为空", trigger: "blur"}
        ],
        earnPrice: [
          {required: true, message: "被叫收益单价不能为空", trigger: "blur"}
        ],
        earnCost: [
          {required: true, message: "被叫收益费用不能为空", trigger: "blur"}
        ],
        remark: [
          {required: true, message: "备注不能为空", trigger: "blur"}
        ],
        record: [
          {required: true, message: "录音信息不能为空", trigger: "blur"}
        ],
        keepLiveTimes: [
          {required: true, message: "心跳上报次数-预留不能为空", trigger: "blur"}
        ],
        priceTimes: [
          {required: true, message: "计费次数-预留不能为空", trigger: "blur"}
        ],
        scoreFlag: [
          {required: true, message: "是否已经评分不能为空", trigger: "blur"}
        ],
        callDate: [
          {required: true, message: "创建日期不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getConfigKeys();
  },
  methods: {
    /** 查询通话话单列表 */
    getList() {
      this.loading = true;
      listCallSheetInfo(this.queryParams).then(response => {
        this.callSheetInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getConfigKeys() {
      getConfigKeys('female_call_permission').then(response => {
        console.log(response);
        this.configKey = response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        type: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        callerId: undefined,
        callerPlat: undefined,
        answerId: undefined,
        answerPlat: undefined,
        ucid: undefined,
        status: undefined,
        ringTime: undefined,
        startTime: undefined,
        stopTime: undefined,
        duration: undefined,
        callPrice: undefined,
        payPrice: undefined,
        payCost: undefined,
        earnPrice: undefined,
        earnCost: undefined,
        remark: undefined,
        record: undefined,
        keepLiveTimes: undefined,
        priceTimes: undefined,
        scoreFlag: undefined,
        callDate: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通话话单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCallSheetInfo(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改通话话单";
      });
    },
    /** 修改按钮操作 */
    switchPermission() {
      var txt;
      if(parseInt(this.configKey) === 0) {
        txt = '是否确认关闭女用户主动呼叫的权限？'
        this.configKey = 1;
      } else {
        txt = '是否确认开启女用户主动呼叫的权限？'
        this.configKey = 0;
      }
      this.$modal.confirm(txt).then(() => {
        this.loading = true;
        updateConfigByKey('female_call_permission', this.configKey);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateCallSheetInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCallSheetInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除通话话单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCallSheetInfo(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/callSheetInfo/export', {
        ...this.queryParams
      }, `callSheetInfo_${new Date().getTime()}.xlsx`)
    },
    /**
     * 点击用户爱动id跳转到用户页面
     * @param platformId
     */
    toUserInfo(platformId) {
      this.$router.push({path: "/user/appUser", query: {id: platformId}});
    },

    /** 刷新正在通话的话单的通话时长 **/
    refreshCallTime(startTime){
      const seconds = Math.round((new Date().getTime() - new Date(startTime).getTime()) / 1000);
      return Math.floor(seconds / 60) + "分钟" + seconds % 60 + "秒";
    },

    /** 删除按钮操作 */
    handleCancel(row) {
      console.log(row)
      this.bo.id = row.id
      this.openCancel = true;
    },

    toCancel() {
      console.log(this.bo)
      cancelCall(this.bo).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.openCancel = false;
        this.getList();
      }).finally(() => {
        this.buttonLoading = false;
      });
    },
  }
};
</script>
